﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

namespace Palsta.Core
{
    public class ViewParser
    {
        #region Members
        /*
         * Inner Members
         */
        protected String _javascriptFileName= "action";
        protected String _htmlFileName = "view";
        protected String _viewFilePath; // View1.xsl file path
        protected XmlDocument _xmlDoc = new XmlDocument(); // Xml document Object
        protected IList<XslHTML> _htmlRootNodes = new List<XslHTML>();  // html root list, there may be multiple template in view1.xsl
        #endregion

        #region Constructors
        public ViewParser(String ViewPath)
        {
            _viewFilePath = ViewPath;
        }
        #endregion

        #region Inner methods
        /// <summary>
        /// Recursion method build the XslElement objects by root first order and save all objects in one list
        /// We don't need to keep the full tree data structor, we only keep the small trees have the calling and called relations.
        /// </summary>
        /// <param name="Node">Xml node</param>
        /// <returns></returns>
        protected virtual XslElement Init(XmlNode Node)
        {
            XslElement parent = XslElementFactory.CreateInstance(Node);
            if (Node.Name.ToLower() == "html")
            {
                _htmlRootNodes.Add((XslHTML)parent);
            }
            foreach (XmlNode child in Node.ChildNodes)
            {
                XslElement s = Init(child);
                if (s != null)
                {
                    s.XmlParent = Node;
                    s.XslParent = parent;
                }
                if (parent == null || s == null)
                {
                    // should add trouble log here, ideally all xsl tags should can be converted xsl elements
                    // if not, that would be a implementation missing
                    continue;
                }
                parent.ChildNoes.Add(s);
            }
            return parent;
        }

        /// <summary>
        /// Recursion method to convert current html node and child nodes into HTML content.
        /// </summary>
        /// <param name="node"></param>
        /// <param name="writer"></param>
        protected virtual void WriteHTMLNode(XslHTML node, StreamWriter writer)
        {
            writer.Write(node.GetHTMLStart() + "\r\n");
            foreach (XslElement el in node.ChildNoes)
            {
                if (el is XslHTML)
                {
                    XslHTML htmlNode = (XslHTML)el;
                    WriteHTMLNode(htmlNode, writer);
                }
            }
            writer.Write(node.GetHTMLEnd() + "\r\n");
        }

        /// <summary>
        /// Recursion method to convert current xsl node and child nodes into JS function
        /// </summary>
        /// <param name="node"></param>
        /// <param name="writer"></param>
        protected virtual void WriteXslNode(XslElement node, StreamWriter writer)
        {
            String function = node.GetFunctionDeclareScript();
            if (function.Length > 0)
            {
                writer.Write(function);
            }
            
            foreach (XslElement el in node.ChildNoes)
            {
                WriteXslNode(el, writer);
            }
        }

        #endregion

        #region Public Methods
        /// <summary>
        /// Public method for initialzation 
        /// </summary>
        /// <returns></returns>
        public virtual Boolean Initialize()
        {
            try
            {
                _xmlDoc.Load(_viewFilePath);
                XmlNodeList htmlTemplates = _xmlDoc.GetElementsByTagName("xsl:template");
                // load all templates and init one by one
                for (int i = 0; i < htmlTemplates.Count; i++)
                {
                    Init(htmlTemplates.Item(i));
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        /// <summary>
        /// Output the javascript functions into js file
        /// The output contains two parts
        /// 1. The function delaration 
        /// 2. Bind function as event listener
        /// </summary>
        /// <param name="OutputPath"></param>
        public virtual void WriteToJS(String OutputPath)
        {
            int index = 0;
            foreach (XslHTML root in _htmlRootNodes)
            {
                index++;
                FileStream stream = new FileStream(OutputPath + _javascriptFileName + "_" + index + ".js", FileMode.Create);
                StreamWriter writer = new StreamWriter(stream);
                try
                {
                    // output functions
                    WriteXslNode(root, writer);
                    // output event map
                    writer.Write("\r\n// Event Maps JSON\r\n");
                    writer.Write(EventObserver.ToJSon());
                }
                catch (Exception e)
                {

                }
                finally
                {
                    writer.Close();
                    stream.Close();
                }
            }
        }

        /// <summary>
        /// Output the html content to html file
        /// </summary>
        /// <param name="OutputPath">Output path</param>
        public virtual void WriteToHTML(String OutputPath)
        {
            int index = 0;
            foreach (XslHTML root in _htmlRootNodes)
            {
                index++;
                FileStream stream = new FileStream(OutputPath + _htmlFileName + "_" + index + ".html", FileMode.Create);
                StreamWriter writer = new StreamWriter(stream);
                try
                {
                    WriteHTMLNode(root, writer);
                }
                catch (Exception e)
                {

                }
                finally
                {
                    writer.Close();
                    stream.Close();
                }
            }
        }
        #endregion
    }
}
